// pages/add/add.js
const app = getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation']  undefined-表示初始化进入该页面 false-表示非初始化进入该页面,且未授权
        if (res.authSetting['scope.userLocation'] != true) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              
            },
            fail: function(error) {
              wx.showModal({
                title: '提示',
                content: '您未开启保定位权限，请点击确定去开启权限！',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                },
                fail: function() {
                  wx.showToast({
                    title: '未获取定位权限，请重新打开设置',
                    icon: 'none',
                    duration: 2000 
                  })
                }
              })
            }
          })
        }
      }
    })
  let server = options.name
  this.setData({
    server
  })
  if(wx.getStorageSync('user')==null||wx.getStorageSync('user')==''||wx.getStorageSync('user')==undefined){
    wx.showModal({
      title: '提示',
      content: '请先完善个人信息',
    success (res) {
   if (res.confirm) {
   console.log('用户点击确定')
   wx.switchTab({
     url: '/pages/user/user',
   })
   } else if (res.cancel) {
   console.log('用户点击取消')
   wx.switchTab({
    url: '/pages/user/user',
  })
  }
  }
})
 }
  if(wx.getStorageSync('user').name&&wx.getStorageSync('user').phone){
    let name = wx.getStorageSync('user').name
    let phone = wx.getStorageSync('user').phone
    db.collection('students').doc(app.globalData.openid).get().then(res=>{
      console.log(res)
      let myMoney = res.data.money
      this.setData({
        name,
        phone,
        myMoney
      })
      })
   
  }else{
    wx.showModal({
      title: '提示',
      content: '请先完善个人信息',
    success (res) {
   if (res.confirm) {
   console.log('用户点击确定')
   wx.switchTab({
     url: '/pages/user/user',
   })
   } else if (res.cancel) {
   console.log('用户点击取消')
   wx.switchTab({
    url: '/pages/user/user',
  })
  }
  }
})
  }
  
  },
  //上传图片
  addImg(){
    let _this = this
    wx.chooseImage({
      count : 1,
      sizeType : ["original","compressed"], 
      sourceType : ["album","camera"],
      success : (chooseres)=>{ 
        console.log(chooseres,'选择图片')
          wx.cloud.uploadFile({
            cloudPath: "img/" + new Date().getTime() +"-"+ Math.floor(Math.random() * 1000),
            filePath : chooseres.tempFilePaths[0],
            success : (res) => { 
              console.log(res,'上传ok')
              wx.showLoading({ 
                title : "图片上传中", 
                mask : true, 
                success : function () {
                    wx.hideLoading() 
                }
              })
            let img = res.fileID
              _this.setData({
                img 
              })
            },
            fail : (err) => {
              console.log(err)
            }
          })
      },
      fail : (err) => {
        console.log(err)
      }
  })
  },
//选择地址
chooseAddress(){
  let _this = this
 
  wx.getSetting({
    success(res) {
      console.log(res)
     if(!res.authSetting['scope.userLocation']){
      wx.openSetting({
        success(res) {
          if (res.authSetting["scope.userLocation"]) {
              wx.chooseLocation({
                    success: (result) => {
                      console.log(result)
                      _this.setData({
                        address:result.name
                      })
                    },
                 })
                }
            }
        })
     }else if (res.authSetting['scope.userLocation']) {
        wx.chooseLocation({
          success: (result) => {
            console.log(result)
            _this.setData({
              address:result.name
            })
          },
       })
      }else {
       wx.openSetting({
          success(res) {
            if (res.authSetting["scope.userLocation"]) {
                wx.chooseLocation({
                      success: (result) => {
                        console.log(result)
                        _this.setData({
                          address:result.name
                        })
                      },
                   })
                  }
              }
          })
      }
    }
  })
 },
//选择时间
 bindTimeChange: function(e) {
  console.log('picker发送选择改变，携带值为', e.detail.value)
  this.setData({
    time: e.detail.value
  })
},
submitOrder(e) {
  let good = e.detail.value
  if(this.data.myMoney - good.money < 0){
   wx.showToast({
     title: '时间币不足，当前剩余'+ this.data.myMoney ,
     icon:'none'
   })
  }else{
    if (!good.time) {
      wx.showToast({
        icon: "error",
        title: '请填写时间'
      })
      return
    }
    if (!good.address) {
      wx.showToast({
        icon: "error",
        title: '请填写地点'
      })
      return
    }
    if (!good.content) {
      wx.showToast({
        icon: "error",
        title: '请填写内容'
      })
      return
    }
    if (!good.money || good.money <= 0) {
      wx.showToast({
        icon: "none",
        title: '请填写价格'
      })
      return
    }
  
    wx.showLoading({
      title: '发布中...',
    })
   if(!this.data.img){
    this.setData({
      img:''
    })
   }
    db.collection('order').add({
      data: {
        type: this.data.server, //类型
        time: good.time, //时间
        address: good.address, //地点
        content: good.content, //内容
        img: this.data.img,
        money: parseInt(good.money), //金额
        status: 0, //状态 0新发布待接单，1已接单待完成，2已完成
        // 发布人
        name: this.data.name,
        phone: this.data.phone,
        _createTime: new Date().getTime() //创建的时间
      },
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: '发布成功',
        })
        console.log('发布成功', res)
        //发布成功以后，减少时间币
        this.removeMoney(good.money)
        wx.switchTab({
          url: '/pages/list/list',
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          icon: 'error',
          title: '网络不给力....'
        })
        console.error('发布失败', err)
      }
    })
  }
},
removeMoney(money2) {
  let money = parseInt(money2)
  let db = wx.cloud.database()
  let _ = db.command
  db.collection('students').doc(app.globalData.openid)
    .update({
      data: {
        money: _.inc(-money)
      }
    }).then(res => {
      console.log('减少金额成功', res)
      if (res.stats && res.stats.updated > 0) {
        wx.cloud.database().collection('jilu').add({
          data: {
            time: app._getCurrentTime(),
            money: '-'+ money,
            openid: app.globalData.openid
          }
        })
      }
    })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})